package fr.mywiki.business.entry;

import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;

import javax.ejb.FinderException;

import fr.mywiki.business.account.AccountLite;
import fr.mywiki.business.account.AccountManager;
import fr.mywiki.business.profil.Profile;
import fr.mywiki.business.structure.StructureLite;
import fr.mywiki.model.ejbAdapter.DataController;
import fr.mywiki.model.queries.QueriesFacade;

/**
 * Contains several methods to manipulate lists of entries.
 * 
 * @author tlombard
 */
public class EntryListManager {
	/**
	 * Returns the list of all the entry identifiers. Should be faster than
	 * ServicesFacade.findAll().
	 * 
	 * @return a <code>Collection</code> of <code>Long</code> objects.
	 */
	public static Collection getAllEntryIds() throws SQLException {
		return QueriesFacade.getAllEntryIds();
	}

	/**
	 * Returns the identifier of an entry, this entry being chosen randomly.
	 * 
	 * @return a <code>Long</code> object representing an entry identifier.
	 * @throws SQLException
	 */
	public static Long getRandomEntryId() throws SQLException {
		ArrayList entryList = new ArrayList(EntryListManager.getAllEntryIds());
		return (Long) entryList.get(new Random().nextInt(entryList.size()));
	}

	/**
	 * Returns the list of all the entries.
	 * 
	 * @return a <code>List</code>
	 */
	protected static List getAllEntries() throws RemoteException {
		return new ArrayList(DataController.findAll(EntryLite.TYPE_ENT));
	}
  
  /**
   * Returns the list of all the entries visible by the current user.
   * 
   * @param account
   *          the connected account. If no one is connected, account is null.
   * @return a <code>Collection</code> of <code>EntryLite</code> objects.
   */
  public static Collection getEntries(AccountLite account) throws RemoteException, SQLException, FinderException {
	  if(account!=null) {
	  // connected user : which profile ?
		Long profileId = account.getProfile().getId();
			if(Profile.ADMIN_PROFILE_ID.equals(profileId))
				return getAllEntries();
			StructureLite structure = AccountManager.getStructure(account);
			if(Profile.AUTHOR_PROFILE_ID.equals(profileId) && structure!=null)
				return EntryAccessManager.getViewableEntries(structure);
	  }
      
  	// unconnected user of unknown profile
    return EntryAccessManager.getUnconnectedViewableEntries();
  }
}
